package y_2025.m05.d23;

import java.io.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class GradeAnalyzer {
    public static void main(String[] args) {
        String inputFile = "grades.txt";
        
        try {
            // 1. 读取成绩文件
            List<double[]> gradesList = readGrades(inputFile);
            
            if (gradesList.isEmpty()) {
                System.out.println("文件中没有成绩数据");
                return;
            }
            
            // 2. 计算均值和方差
            int numCourses = gradesList.get(0).length;
            double[] means = new double[numCourses];
            double[] variances = new double[numCourses];
            
            calculateStatistics(gradesList, means, variances);
            
            // 3. 格式化结果并追加到文件
            String resultLine = formatResult(means, variances);
            appendResultToFile(inputFile, resultLine);
            
            System.out.println("分析结果已追加到文件: " + inputFile);
            
        } catch (IOException e) {
            System.err.println("处理文件时出错: " + e.getMessage());
        }
    }
    
    private static List<double[]> readGrades(String filename) throws IOException {
        List<double[]> gradesList = new ArrayList<>();
        
        try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
            String line;
            while ((line = reader.readLine()) != null) {
                // 跳过空行和已经包含结果的行
                if (line.trim().isEmpty() || line.startsWith("均值和方差")) {
                    continue;
                }
                
                String[] parts = line.split("\\s+");
                if (parts.length < 2) continue; // 至少学号和一门成绩
                
                double[] grades = new double[parts.length - 1]; // 去掉学号
                for (int i = 0; i < grades.length; i++) {
                    try {
                        grades[i] = Double.parseDouble(parts[i + 1]);
                    } catch (NumberFormatException e) {
                        System.err.println("无效的成绩格式: " + line);
                        grades[i] = 0; // 无效成绩视为0
                    }
                }
                gradesList.add(grades);
            }
        }
        
        return gradesList;
    }
    
    private static void calculateStatistics(List<double[]> gradesList, double[] means, double[] variances) {
        int numStudents = gradesList.size();
        int numCourses = means.length;
        
        // 计算总和
        for (double[] grades : gradesList) {
            for (int i = 0; i < numCourses; i++) {
                means[i] += grades[i];
            }
        }
        
        // 计算均值
        for (int i = 0; i < numCourses; i++) {
            means[i] /= numStudents;
        }
        
        // 计算方差
        for (double[] grades : gradesList) {
            for (int i = 0; i < numCourses; i++) {
                double diff = grades[i] - means[i];
                variances[i] += diff * diff;
            }
        }
        
        // 计算方差均值
        for (int i = 0; i < numCourses; i++) {
            variances[i] /= numStudents;
        }
    }
    
    private static String formatResult(double[] means, double[] variances) {
        DecimalFormat df = new DecimalFormat("#.#");
        StringBuilder sb = new StringBuilder("均值和方差 ");
        
        for (int i = 0; i < means.length; i++) {
            sb.append(df.format(means[i]))
              .append("/")
              .append(df.format(variances[i]))
              .append(" ");
        }
        
        return sb.toString().trim();
    }
    
    private static void appendResultToFile(String filename, String result) throws IOException {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename, true))) {
            writer.newLine();
            writer.write(result);
        }
    }
}